<?php
use Lib\ResLoader;
class App_Plugin_Acl extends Zend_Controller_Plugin_Abstract
{
    /**
     * @var Zend_Auth
     */
    protected $_auth = null;

    /**
     * @var Zend_Acl
     */
    protected $_acl = null;

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        return false;
        $this->_acl = $this->createAcl();
        $this->_auth = Zend_Auth::getInstance();
        // Setting user role
        $role = 'guest';
        if ($this->_auth->hasIdentity()) {
            $user = $this->_auth->getStorage()->read();
            $userManager = new \Managers\Users();
            $userRole = $userManager->getRole($user->id);
            if ($userRole) {
                $role = $userRole['name'];
            }
        }
        // Mapping to determine which Resource the current
        // request refers to (really simple for this example!)
        $resource = $request->controller;
        $privilege = $request->action;

        if (!$this->_acl->has($resource)) {
            $resource = null;
        }

        // ACL Access Check
//        if (!$this->_acl->isAllowed($role, $resource, $privilege)) {
//            $request->setControllerName('index');
//            $request->setActionName('login');
//        }
    }

    /**
     * @param \Zend_Acl $acl
     * @return void
     */
    public function setAcl($acl)
    {
        $this->_acl = $acl;
    }

    /**
     * @return \Zend_Acl
     */
    public function getAcl()
    {
        return $this->_acl;
    }

    /**
     * @param \Zend_Auth $auth
     * @return void
     */
    public function setAuth($auth)
    {
        $this->_auth = $auth;
    }

    /**
     * @return \Zend_Auth
     */
    public function getAuth()
    {
        return $this->_auth;
    }

    /**
     * Возвращает Zend_Acl с правами, ресурсами, ролями полученными с базы.
     * @return Zend_Acl
     */
    public function createAcl()
    {

        $acl = new Zend_Acl();
        $aclManager = new \Managers\Acl();
        $roles = $aclManager->getRolesList();
        $resources = $aclManager->getResourcesList();
        $allows = $aclManager->getRoleResourceList();

        $acl = $this->addRoles($acl, $roles);
        $acl = $this->addResources($acl, $resources);
        $acl = $this->addAllowList($acl, $allows);

        return $acl;

    }

    /**
     * Добавляет к $acl заданный массив ролей..
     * @param Zend_Acl $acl
     * @param array $roles
     * @param null|string $parent
     * @return Zend_Acl
     */
    private function addRoles($acl, $roles, $parent = null)
    {
        foreach ($roles as $role) {
            if ($parent) {
                $acl->addRole(new Zend_Acl_Role($role['name']), $parent);
            } else {
                $acl->addRole(new Zend_Acl_Role($role['name']));
            }
            $this->addRoles($acl, $role['children'], $role['name']);
        }
        return $acl;
    }

    /**
     * Добавляет к $acl заданный массив ресурсов.
     * @param Zend_Acl $acl
     * @param array $resources
     * @param null|string $parent
     * @return Zend_Acl
     */
    private function addResources($acl, $resources, $parent = null)
    {
        foreach ($resources as $resource) {
            if ($parent) {
                $acl->add(new Zend_Acl_Resource($resource['name']), $parent);
            } else {
                $acl->add(new Zend_Acl_Resource($resource['name']));
            }
            $this->addResources($acl, $resource['children'], $resource['name']);
        }

        return $acl;
    }

    /**
     * Добавляет к $acl заданный массив правил.
     * @param Zend_Acl $acl
     * @param array $allowsList
     * @return Zend_Acl
     */
    private function addAllowList($acl, $allowsList)
    {
        foreach ($allowsList as $allow) {
            $acl->allow($allow['aclRole']['name'], $allow['aclResource']['name'], $allow['privilege']);
        }

        return $acl;
    }

    /**
     * Возвращает массив представление пользователя.
     * @return array
     */
    public function getUser()
    {
        $userSession = new Zend_Session_Namespace('usersession');
        $user_id = $userSession->user_id;

        if (isset($user_id)) {
            $userManager = new \Managers\Users();
            $user = $userManager->getById($user_id);
            return $user;
        } else {
            $guest = array('id' => 0,
                           'name' => 'guest',
                           'role' => array('name' => 'guest'));
            return $guest;
        }
    }
}
